如果bean本身要通过某种动态的过程来确定和提供资源路径,那么bean可能需要使用ResourceLoader
接口来加载资源。比如加载某种类型的模板,到底需要那种资源取决于不同的用户。如果资源是静态的,那么完全消除ResourceLoader接口的使用是有意义的,只要让bean暴露它所需要的Resource属性,然后让资源注入到它当中。
所有的应用程序上下文都注册并使用一个特殊的JAVA BEANS PropertyEditor
,可以将String
转换成Resource
,这让注入资源变得很轻松。比如,myBean
有一个Resource
属性,可以像下列这样简单用一个String
来表示Resource
:
<bean id="myBean" class="...">
<property name="template" value="some/resource/path/myTemplate.txt"/>
</bean>
注意到,组员路径没有特定的前缀,所以应用程序上下文作为ResourceLoader
时,将根据自身的类型将资源加载为ClassPathResource
,FileSystemResource
,或ServletContextResource
。
如果需要强制使用特指的Resource
,那么需要指定前缀。下面两个例子展示了如何转成ClassPathResource
和UrlResouce
(后者用来访问文件系统):
<property name="template" value="classpath:some/resource/path/myTemplate.txt">
<property name="template" value="file:///some/resource/path/myTemplate.txt"/>